﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Drawing;

namespace iPhoneUI
{
    public static class XmlNodeExtensions
    {
        public static IEnumerable<T> Convert<T>(this XmlNode node, Func<XmlNode, T> convert, string xpath)
        {
            Debug.Assert(node != null);

            List<T> list = new List<T>();
            foreach (XmlNode n in node.SelectNodes(xpath))
                list.Add(convert(n));

            return list;
        }

        public static int Position(this XmlNode node, XmlNodeList list)
        {
            Debug.Assert(list != null);
            
            int i = 0;
            foreach (XmlNode test in list)
            {
                if (object.ReferenceEquals(node, test))
                    return i;

                i++;
            }

            return -1;
        }

        public static int Position(this XmlNode node)
        {
            return node.Position(node.ParentNode.SelectNodes("*"));
        }

        public static object CoerceInnerText(this XmlNode node, Type type)
        {
            Debug.Assert(node != null);
            string s = node.InnerText;

            if (string.IsNullOrEmpty(s) == false)
            {
                if (type.IsEnum)
                    return (Enum)Enum.Parse(type, s, true);

                if (type == typeof(bool))
                    return XmlConvert.ToBoolean(s);

                if (type == typeof(byte))
                    return XmlConvert.ToByte(s);

                if (type == typeof(int))
                    return XmlConvert.ToInt32(s);

                if (type == typeof(double))
                    return XmlConvert.ToDouble(s);

                if (type == typeof(DateTime))
                    return XmlConvert.ToDateTime(s, XmlDateTimeSerializationMode.Local);

                if (type == typeof(Color))
                    return GetKnownColor(s);
            }

            return s;
        }

        private static Color GetKnownColor(string color)
        {
            // use reflection to find the associated static property on the Color type
            PropertyInfo property = typeof(Color).GetProperty(color, BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);
            if (property != null)
                return (Color)property.GetValue(typeof(Color), null);

            return Color.White;
        }
    }
}
